# 使用QT搭建界面，点击上传图像按钮，上传图像，还另外有以下按钮可供操作【灰度化、浮雕滤镜、二值化】，也可补充自己感兴趣的算法按钮。
import sys

from PyQt6.QtGui import QPixmap

import deal_image as dm
from PyQt6 import uic
from PyQt6.QtWidgets import QWidget, QApplication, QPushButton, QLabel, QFileDialog, QInputDialog

file_name = ""


class My_Widget(QWidget):
    def __init__(self):
        super().__init__()

        ui = uic.loadUi("image.ui", self)

        # 加载组件
        self.upload_image: QPushButton = ui.upload_image
        self.gray_btn: QPushButton = ui.gray_btn
        self.FuDiao_btn: QPushButton = ui.fudiao_btn
        self.binary_btn: QPushButton = ui.binary_btn
        self.image1: QLabel = ui.image1
        self.image2: QLabel = ui.image2

        # 建立联系
        self.upload_image.clicked.connect(self.upload_image_clicked)
        self.gray_btn.clicked.connect(self.gray)
        self.FuDiao_btn.clicked.connect(self.fu_diao)
        self.binary_btn.clicked.connect(self.binary)

    def upload_image_clicked(self):
        global file_name
        file_name, file_type = QFileDialog.getOpenFileName(self, "选择图片", "", "*.png;;*.jpg;;*.jpeg;;*.bmp")
        print(file_name)
        self.image1.setPixmap(QPixmap(file_name))
        # 设置图片自适应
        self.image1.setScaledContents(True)

    def gray(self):
        if file_name == "":
            return
        save_gray_path = dm.gray(file_name)
        self.image2.setPixmap(QPixmap(save_gray_path))
        self.image2.setScaledContents(True)

    def fu_diao(self):
        if file_name == "":
            return
        save_fu_diao_path = dm.fu_diao(file_name)
        self.image2.setPixmap(QPixmap(save_fu_diao_path))
        self.image2.setScaledContents(True)

    def binary(self):
        item = self.getItem()
        if file_name == "":
            return
        save_binary_path = dm.binary(file_name, item)
        self.image2.setPixmap(QPixmap(save_binary_path))
        self.image2.setScaledContents(True)

    def getItem(self):
        items = ("二值化阈值处理", "反二值化阈值处理", "截断阈值处理", "低于阈值归零处理", "高于阈值归零处理")
        # 返回两个值，第一个item代表用户选择的值，ok代表用户是否按下了取消
        item, ok = QInputDialog.getItem(self, "请选择阈值处理方式", "方式列表", items)
        if ok and item:
            return item


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = My_Widget()
    window.show()
    sys.exit(app.exec())
